package com.flyone.qybackend.utils;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.google.gson.Gson;
import com.flyone.qybackend.model.entity.ATA;
import com.flyone.qybackend.model.entity.baiduToken;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


/**
 * 百度云API工具类
 * 情感倾向分析API
 */
@Component
public class AipNIpUtils {
    //设置APPID/AK/SK
    @Value("${baiduyun.apiKey}")
    private String apiKey;
    @Value("${baiduyun.secretKey}")
    private String secretKey;
    /**
     * 获得access-token
     */
    public String getAccessToken(){
        String url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&" +
                "client_id="+apiKey+"&" +
                "client_secret="+secretKey;
        String res = HttpRequest.post(url)
                .body("application/json")
                .execute().body();
        Gson gson = new Gson();
        baiduToken baiduToken = gson.fromJson(res, baiduToken.class);
        return baiduToken.getAccess_token();
    }

    /**
     * 调用情感分析API
     */
    public ATA sentimentClassify(String text, String accessToken){
        String url = "https://aip.baidubce.com/rpc/2.0/nlp/v1/sentiment_classify?access_token="+ accessToken +"&charset=UTF-8";
        ATA content = new ATA();
        content.setText(text);
        Gson gson = new Gson();
        String json = gson.toJson(content);
        String result = HttpRequest.post(url)
                .header(Header.CONTENT_TYPE, "application/json")
                .body(json).execute().body();
        ATA ata = gson.fromJson(result, ATA.class);
        System.out.println(ata);
        return ata;
    }
}
